package com.tom.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Component
public class LoginCheckFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE; // 前置拦截器
    }
    /**
    * @Title:
    * @Description: 优先级
    */
    @Override
    public int filterOrder() {
        return 1;
    }
    /**
    * @Description: 判断是否要执行run 方法检查
    */
    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取路径
        String url = request.getRequestURI();
        if (url.endsWith("/login")||url.endsWith("/register")||url.contains("/static/")){
            return false;
        }
        return  true;
    }
    
    /** 
    * @Title:
    * @Description: 判断是否登录过
    */
    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        String token = request.getHeader("token");
        // 判断是否为空
        if (StringUtils.isBlank(token)) {
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("success" , false);
            resultMap.put("message" , "请先登录");
            //中文编码
            response.setContentType("application/json;charset=utf-8");
            //把map转成json字符串，写到浏览器
            String resultJsonString = JSON.toJSONString(resultMap);
            // 设置状态码
            response.setStatus(404);
            try {
                // 把json字符串传入响应体
                response.getWriter().print(resultJsonString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 设置zuul的响应为false 就是拦截
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    };
}
